package com.zzyl.nursing.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.framework.config.properties.HuaWeiIotConfigProperties;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.service.IDeviceService;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import com.zzyl.system.service.ISysUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 设备信息Service业务层处理
 *
 * @author xs
 * @date 2025-10-23
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IoTDAClient client;
    @Autowired
    private CacheConstants cacheConstants;

    /**
     * 查询设备信息
     *
     * @param id 设备信息主键
     * @return 设备信息
     */
    @Override
    public Device selectDeviceById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备信息列表
     *
     * @param device 设备信息
     * @return 设备信息
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    @Override
    public void syncProductList() {
        //对接华为云API，获取产品列表

        ListProductsResponse response = client.listProducts(new ListProductsRequest());
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("同步产品列表异常");
        }

        //将获取到的产品列表转为JSON字符串，存入Redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_PRODUCT_LIST_KEY, JSONUtil.toJsonStr(response.getProducts()));
    }

    @Override
    public List<ProductVo> allProduct() {
        //从Redis查询产品列表JSON字符串
        String productListJson = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StringUtils.isBlank(productListJson)) {
            return Collections.emptyList();
        }

        //解析JSON为产品列表
        List<ProductSummary> productList = JSONUtil.toList(productListJson, ProductSummary.class);

        //遍历产品列表，转为前端需要的数据类型
        List<ProductVo> productVoList = productList.stream().map(x -> {
            return ProductVo.builder().productKey(x.getProductId()).productName(x.getName()).build();
        }).collect(Collectors.toList());

        return productVoList;
    }

    /**
     * 注册设备
     *
     * @param dto
     */
    /**
     * 注册设备
     *
     * @param dto
     */
    @Transactional
    @Override
    public void register(DeviceDto dto) {
        //前端没有传设备标识码，生成雪花算法值，当做唯一设备标识码
        String nodeId = IdUtil.getSnowflakeNextIdStr();
        //设备备注名称（设备描述）
        String deviceDescription = dto.getNickname();

        //检查设备名是否重复
        Long countDeviceName = this.lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName()).count();
        if (countDeviceName > 0) {
            throw new BaseException("设备重名");
        }

        //检查设备标识是否重复（这一步不查也行，因为设备标识码每次生成完全不一样）
        Long countNodeId = this.lambdaQuery().eq(Device::getNodeId, nodeId).count();
        if (countNodeId > 0) {
            throw new BaseException("设备标识重复");
        }

        //检查当前位置是否绑定过相同产品
        Long countLocation = this.lambdaQuery()
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getProductKey, dto.getProductKey())
                .count();
        if (countLocation > 0) {
            throw new BaseException("当前位置绑定过相同产品");
        }

        //注册设备到华为云IOT平台
        AddDeviceRequest addDeviceRequest = new AddDeviceRequest();
        AddDevice addDevice = new AddDevice();
        addDevice.setProductId(dto.getProductKey());
        addDevice.setDeviceName(dto.getDeviceName());
        //设备备注名称（设备描述）
        addDevice.setDescription(deviceDescription);
        //雪花算法值当做唯一设备标识码
        addDevice.setNodeId(nodeId);

        AuthInfo authInfo = new AuthInfo();
        //uuid当做唯一设备密钥
        String secret = IdUtil.simpleUUID();
        authInfo.setSecret(secret);
        addDevice.setAuthInfo(authInfo);

        addDeviceRequest.setBody(addDevice);
        AddDeviceResponse response = client.addDevice(addDeviceRequest);
        //注意这个IOT的接口响应201表示创建成功，不是传统的200
        if (response.getHttpStatusCode() != 201) {
            throw new BaseException("注册设备到华为IOT失败");
        }

        //保存设备到表中
        Device device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setNodeId(nodeId);//前面生成的设备标识码
        device.setIotId(response.getDeviceId());//设备ID由物联网平台分配获得，生成规则为product_id + _ + node_id拼接而成
        device.setNickname(deviceDescription);//设备备注名称（设备描述）
        device.setDeviceDescription(deviceDescription);//设备备注名称（设备描述）
        device.setSecret(secret);//前面生成的设备密钥

        String productName = this.getProductNameFromCache(dto.getProductKey());
        device.setProductName(productName);//产品名称
        this.save(device);
    }


    /**
     * 从缓存中根据产品ID获取产品名
     *
     * @param productAppId
     * @return
     */
    private String getProductNameFromCache(String productAppId) {
        //从Redis查询产品列表JSON字符串
        String productListJson = redisTemplate.opsForValue().get(CacheConstants.IOT_PRODUCT_LIST_KEY);
        if (StringUtils.isBlank(productListJson)) {
            return null;
        }

        //解析JSON为产品列表
        List<ProductSummary> productList = JSONUtil.toList(productListJson, ProductSummary.class);
        ProductSummary product = productList.stream().filter(x -> productAppId.equals(x.getProductId())).findFirst().get();
        return product.getName();
    }

    @Autowired
    private ISysUserService userService;
    @Autowired
    private HuaWeiIotConfigProperties huaWeiIotConfigProperties;

    /**
     * 获取设备详细信息
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //根据设备ID从表中查询设备，不存在抛异常
        Device device = this.lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device == null) {
            throw new BaseException("设备不存在");
        }

        //拷贝表中设备数据给VO
        DeviceDetailVo vo = BeanUtil.toBean(device, DeviceDetailVo.class);

        vo.setDeviceSecret(device.getSecret());
        vo.setGmtCreate(device.getCreateTime());
        vo.setCreator(userService.selectUserById(Long.valueOf(device.getCreateBy())).getUserName());
        vo.setRegion(huaWeiIotConfigProperties.getRegionId());

        //调用华为IOT平台接口查询设备
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.withDeviceId(iotId);//查询数据form华为云平台
        try {
            ShowDeviceResponse response = client.showDevice(request);
            if (response == null) {
                throw new BaseException("调用华为IO接口查询设备详情失败");
            }

            //拷贝华为中的设备数据给VO
            BeanUtils.copyProperties(response, vo);
            vo.setDeviceStatus(response.getStatus()); //设备状态
            //激活时间,格式：yyyy-MM-dd HH:mm:ss (@JsonFormat注解上加了)。 而华为响应的激活时间格式为：2019-03-03T08:10:111Z
            String activeTime = response.getActiveTime();
            if (StringUtils.isNotBlank(activeTime)) {
                LocalDateTime gmtActive = OffsetDateTime.parse(activeTime)
                        .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                        .toLocalDateTime();
                vo.setGmtActive(gmtActive);
            }
            if (StringUtils.isNotBlank(response.getFwVersion())) {
                vo.setFirmwareVersion(response.getFwVersion());//固件版本
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("调用华为IO接口查询设备详情失败");
        }

        return vo;

    }


    /**
     * 查看指定产品的已发布物模型中的功能定义详情
     *
     * @return
     */
    @Override
    public JSONObject queryProductModelInfo(String productKey) {
        //参数校验
        if (StringUtils.isEmpty(productKey)) {
            throw new BaseException("请输入正确的参数");
        }
        //调用华为云物联网接口
        ShowProductRequest showProductRequest = new ShowProductRequest();
        showProductRequest.setProductId(productKey);
        ShowProductResponse response;

        try {
            response = client.showProduct(showProductRequest);
        } catch (Exception e) {
            throw new BaseException("查询产品详情失败");
        }

        JSONObject productModelInfo = null;

        //判断是否存在服务数据
        List<ServiceCapability> serviceCapabilityList = response.getServiceCapabilities();
        if (CollUtil.isNotEmpty(serviceCapabilityList)) {
            productModelInfo = JSONUtil.parseObj(serviceCapabilityList.get(0));
        }
        return productModelInfo;
    }


    /**
     * 查询指定设备的物模型运行状态
     *
     * @return
     */
    @Override
    public AjaxResult queryDevicePropertyStatus(String productKey, String deviceName) {

        //根据产品Id和设备名查询设备ID
        Device device = this.lambdaQuery().eq(Device::getProductKey, productKey).eq(Device::getDeviceName, deviceName).one();
        if (device == null) {
            throw new BaseException("没有此设备");
        }

        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(device.getIotId());//根据设备ID查询影子设备的信息
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询设备上报数据，调用失败");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        //返回数据
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        List<Map<String, Object>> list = new ArrayList<>();

        //处理上报时间日期
        LocalDateTime eventTime = OffsetDateTime.parse(shadow.get(0).getReported().getEventTime(),
                        DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmssX")
                )
                .atZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();

        jsonObject.forEach((k, v) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("identifier", k);
            map.put("value", v);
            map.put("time", eventTime);
            list.add(map);
        });

        Map<String, Object> propertyStatusInfo = new HashMap<>();
        propertyStatusInfo.put("propertyStatusInfo", list);

        Map<String, Object> result = new HashMap<>();
        result.put("list", propertyStatusInfo);

        return AjaxResult.success(result);
    }

    @Override
    public void updateDevice(DeviceDto dto) {
        //拷贝DTO数据给实体,修改备注名称也就是中文名称
        Device device = BeanUtil.toBean(dto, Device.class);
        this.updateById(device);
        //2.0 给他new一个UpdateDeviceRequest
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        // 3.设备ID传递
        request.setDeviceId(device.getIotId());
        UpdateDevice updateDevice = new UpdateDevice();
        updateDevice.setDescription(device.getNickname());
        request.setBody(updateDevice);
        try {
            //1. 调用华为云接口修改设备中文名称,他需要一个UpdateDeviceRequest
            client.updateDevice(request);
        } catch (Exception e) {
            throw new BaseException("调用云平台失败");
        }
    }

@Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteDevice(DeviceDto dto) {
        this.lambdaUpdate().eq(Device::getIotId, dto.getIotId()).remove();

        //删除华为云端
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(dto.getIotId());
        try {
            client.deleteDevice(request);
        } catch (Exception e) {
            throw new BaseException("调用华为云接口删除设备失败");
        }

    }
}
